package Threads.ReentrantLock.abcabcabc;



//用wait notify实现交替打印
public class wait_nofity {
    public static void main(String[] args) throws InterruptedException {
        Sync sync=new Sync(1,5);
        new Thread(()->{
            try {
                sync.print(1,2,"a");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                sync.print(2,3,"b");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                sync.print(3,1,"c");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
    static class Sync{
        private int flag;
        private int loopCount;

        public Sync(int flag,int loopCount){
            this.flag=flag;
            this.loopCount=loopCount;
        }

        public void print(int waitFlag,int nextFlag,String str) throws InterruptedException {
            for (int i=0;i<loopCount;i++){
                synchronized (this){
                    while (this.flag!=waitFlag)
                        this.wait();
                    System.out.println(str);
                    flag=nextFlag;
                    this.notifyAll();
                }
            }
        }
    }
}
